package com.xuetang9.fujian.view;

import com.xuetang9.fujian.mychat.entity.BizType;
import com.xuetang9.fujian.mychat.util.SysDTO;
import com.xuetang9.fujian.net.ClientV1;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;

/**
 * @author: fujian
 * @description:
 * @date: 2021/5/11 8:45
 * @version: V1.0
 * @package: com.xuetang9.fujian.view
 **/
public class LoginFrame extends JFrame {
    private JLabel lblLoginName = new JLabel("登录名：");
    private JLabel lblLoginPwd = new JLabel("登录密码：");
    private JTextField txtLoginName = new JTextField();
    private JPasswordField txtLoginPwd = new JPasswordField();
    private JButton btnLogin = new JButton("登录");
    private ClientV1 client = null;
    private JPanel contentPanel;
    public LoginFrame() throws HeadlessException {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(500,400);
        contentPanel = (JPanel) getContentPane();
        contentPanel.setLayout(null);
        initComponents();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void initComponents() {
        lblLoginName.setBounds(50,50,120,20);
        lblLoginPwd.setBounds(50,90,120,20);
        txtLoginName.setBounds(150,50,120,25);
        txtLoginPwd.setBounds(150,90,120,25);
        btnLogin.setBounds(100,130,80,25);
        contentPanel.add(lblLoginName);
        contentPanel.add(lblLoginPwd);
        contentPanel.add(txtLoginName);
        contentPanel.add(txtLoginPwd);
        contentPanel.add(btnLogin);

        btnLogin.addActionListener(e->{
            btnLoginActionPerformed();
        });
    }

    private void btnLoginActionPerformed() {
        // 进行界面的输入验证
        // 构建发送给服务端的DTO对象
        // 实例化客户端对象发送DTO对象，并接收服务端的返回
        // 根据服务端返回的结果显示相应的界面逻辑
        SysDTO dto = new SysDTO(BizType.登录);
        dto.setNickName(txtLoginName.getText());
        dto.setPassword(new String(txtLoginPwd.getPassword()));
        if (null == this.client){
            this.client = new ClientV1("localhost",8888);
        }
        try {
            dto = client.sendAndReceive(dto);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        if (dto.getBizType() == BizType.登录成功){
            // 隐藏当前窗体，显示聊天窗体
            this.setVisible(false);
            new ChatFrame(dto.getUser(),this.client);
//            JOptionPane.showMessageDialog(this,"登录成功");
        }else {
            JOptionPane.showMessageDialog(this,"登录失败，请检查用户名密码");
        }
    }

    public static void main(String[] args) {
        Font defaultFont = new Font("微软雅黑",Font.BOLD,18);
        UIManager.put("Label.font",defaultFont);
        UIManager.put("Button.font",defaultFont);
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new LoginFrame();
            }
        });
    }
}
